package com.zenithmind.gateway.logging;

import com.zenithmind.gateway.auth.TokenExtractor;
import com.zenithmind.gateway.auth.UserInfoParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

/**
 * 默认请求信息提取器实现
 * 专门负责从HTTP请求中提取日志所需的信息
 * 遵循单一职责原则：只负责请求信息的提取逻辑
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DefaultRequestInfoExtractor implements RequestInfoExtractor {
    
    private final TokenExtractor tokenExtractor;
    private final UserInfoParser userInfoParser;

    @Override
    public String extractUserId(ServerHttpRequest request) {
        try {
            String token = tokenExtractor.extractToken(request);
            if (token != null) {
                UserInfoParser.UserInfo userInfo = userInfoParser.parseUserInfo(token);
                return userInfo.getUserId();
            }
        } catch (Exception e) {
            log.trace("提取用户ID失败", e);
        }
        return null;
    }

    @Override
    public String extractUsername(ServerHttpRequest request) {
        try {
            String token = tokenExtractor.extractToken(request);
            if (token != null) {
                UserInfoParser.UserInfo userInfo = userInfoParser.parseUserInfo(token);
                // 从claims中提取用户名，这里假设用户名存储在claims中
                Object username = userInfo.getClaims().get("username");
                return username != null ? username.toString() : null;
            }
        } catch (Exception e) {
            log.trace("提取用户名失败", e);
        }
        return null;
    }

    @Override
    public String extractRemoteAddress(ServerHttpRequest request) {
        if (request.getRemoteAddress() != null) {
            return request.getRemoteAddress().getHostString();
        }
        return "unknown";
    }
}
